﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace AIC_PN
{
    public partial class BaoCaoDinhKem_Update : System.Web.UI.Page
    {
        private int IDDonVi;
        private int IDTenBaoCao;
        private int IDKyBaoCao;
        private static int IDBaoCao;
        private static string FilePath = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPermission();
            if (!IsPostBack)
            {
                BindDataToDropDownList(ddlKyBaoCao, "KyBaoCao");
                BindDataToDropDownList(ddlTenBaoCao, "BaoCaoDinhKem");
                ddlKyBaoCao.Items.Insert(0, new ListItem("Chọn kỳ báo cáo", "-1"));
                ddlTenBaoCao.Items.Insert(0, new ListItem("Chọn tên báo cáo", "-1"));
                lblDonVi.Text = MyCommon.GetTenDonVi(Session["userid"].ToString());
            }

        }

        private void CheckPermission()
        {
            Dictionary<string, int> Role = MyCommon.CheckPermission("CacBaoCaoDinhKem");
            if (Role == null || Role["Xem"] == 0 || ((Role["Xem"] == 1 && Role["Sua"] == 0)))
            {
                Response.Redirect("Index.aspx?p=0");
            }
        }

        protected int ThemMoiBaoCao(int BaoCaoAttachID_DM, int KyBaoCaoID_DM, string TenBaoCao, string NoiDung, string FileDinhKem, int UserID)
        {
            string sql = "INSERT INTO dbo.tblBaoCaoAttach( BaoCaoAttachID_DM ,KyBaoCaoID_DM ,DonVi_ID ,TenBaoCao ,NoiDung ,FileDinhKem ,CreateDate ,UpdateDate ,UserID) " +
                             "VALUES  ( @BaoCaoAttachID_DM ,@KyBaoCaoID_DM ,@DonVi_ID ,@TenBaoCao ,@NoiDung ,@FileDinhKem ,GETDATE() ,GETDATE() ,@UserID )";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@BaoCaoAttachID_DM", SqlDbType.Int, ParameterDirection.Input, BaoCaoAttachID_DM));
            arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCaoID_DM));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonVi_ID", SqlDbType.Int, ParameterDirection.Input, Convert.ToInt32(MyCommon.GetDonViID(UserID.ToString()))));
            arrParams.Add(SqlHelper.CreateParameterObject("@TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, TenBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, NoiDung));
            arrParams.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FileDinhKem));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            return SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected int CapNhatBaoCao(string TenBaoCao, string NoiDung, string FileDinhKem, int IDBaoCao, int Us)
        {
            string sql = "UPDATE dbo.tblBaoCaoAttach SET TenBaoCao = @TenBaoCao, FileDinhKem = @FileDinhKem, NoiDung = @NoiDung WHERE ID = @IDBaoCao";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, TenBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, NoiDung));
            arrParams.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FileDinhKem));
            arrParams.Add(SqlHelper.CreateParameterObject("@IDBaoCao", SqlDbType.Int, ParameterDirection.Input, IDBaoCao));
            return SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected int CapNhatBaoCao(string TenBaoCao, string NoiDung, int IDBaoCao, int UserID, string FileDinhKem)
        {
            string dinhkem = "";
            if (FileDinhKem != "")
            {
                dinhkem = "FileDinhKem = @FileDinhKem,";
            }
            string sql = "UPDATE dbo.tblBaoCaoAttach SET TenBaoCao = @TenBaoCao, NoiDung = @NoiDung, " +
                         "UpdateDate = GETDATE()," + dinhkem + " UserID = @UserID WHERE ID = @IDBaoCao";
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenBaoCao", SqlDbType.NVarChar, ParameterDirection.Input, TenBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@NoiDung", SqlDbType.NVarChar, ParameterDirection.Input, NoiDung));
            arrParams.Add(SqlHelper.CreateParameterObject("@IDBaoCao", SqlDbType.Int, ParameterDirection.Input, IDBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@UserID", SqlDbType.Int, ParameterDirection.Input, UserID));
            arrParams.Add(SqlHelper.CreateParameterObject("@FileDinhKem", SqlDbType.NVarChar, ParameterDirection.Input, FileDinhKem));
            return SqlHelper.ExecuteNonQuery(CommandType.Text, sql, arrParams);
        }

        protected void btnXemCiTiet_Click(object sender, EventArgs e)
        {

            if (btnXemCiTiet.CommandArgument == MyConst.Action.Addnew)
            {
                try
                {
                    int UserID = Convert.ToInt32(Session["userid"]);

                    int BaoCaoAttachID_DM = Convert.ToInt32(ddlTenBaoCao.SelectedValue);
                    int KyBaoCaoID_DM = Convert.ToInt32(ddlKyBaoCao.SelectedValue);
                    string TenBaoCao = txtTenBaoCao.Text;
                    string NoiDung = txtNoiDung.Value;
                    string FileDinhKem = UploadFile();

                    ThemMoiBaoCao(BaoCaoAttachID_DM, KyBaoCaoID_DM, TenBaoCao, NoiDung, FileDinhKem, UserID);
                    MyCommon.AddMessage(this.Master, "Tạo mới thành công Báo cáo : " + TenBaoCao, MyConst.MessageType.Success);
                }
                catch (Exception)
                {
                    MyCommon.AddMessage(this.Master, "Tạo mới xảy ra lỗi", MyConst.MessageType.Error);
                }
            }
            else if (btnXemCiTiet.CommandArgument == MyConst.Action.Update)
            {
                try
                {
                    int UserID = Convert.ToInt32(Session["userid"]);
                    string TenBaoCao = txtTenBaoCao.Text;
                    string NoiDung = txtNoiDung.Value;
                    string FileDinhKem = UploadFile();
                    CapNhatBaoCao(TenBaoCao, NoiDung, IDBaoCao, UserID, FileDinhKem);
                    MyCommon.AddMessage(this.Master, "Cập nhật thành công Báo cáo : " + TenBaoCao, MyConst.MessageType.Success);
                }
                catch (Exception)
                {
                    MyCommon.AddMessage(this.Master, "Cập nhật xảy ra lỗi", MyConst.MessageType.Error);
                }
            }
        }

        private string UploadFile()
        {
            try
            {
                if (fulFileDinhKem.HasFile)
                {
                    if (fulFileDinhKem.PostedFile.ContentLength < 2100000)
                    {
                        string sFolderPath = Server.MapPath(@"userfiles/BaoCao");
                        HttpPostedFile myFile = fulFileDinhKem.PostedFile;
                        string sFileName = myFile.FileName;
                        string[] arrFileName = sFileName.Split('.');
                        arrFileName[0] = DateTime.Now.ToString("ddMMyyhhssmm");
                        sFileName = arrFileName[0] + "." + arrFileName[1];
                        myFile.SaveAs(string.Format(@"{0}\{1}", sFolderPath, sFileName));
                        return "userfiles/BaoCao/" + sFileName;
                    }
                    else
                    {
                        return "";
                    }
                }
                else
                {
                    return "";
                }
            }
            catch (Exception)
            {
                return "";
            }
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("index.aspx");
        }

        protected void BindDataToDropDownList(DropDownList BindDropDown, string MaDM)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@MaDM", SqlDbType.NVarChar, ParameterDirection.Input, MaDM));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblDanhMuc WHERE MaDM=@MaDM", arrParams);
            BindDropDown.DataSource = dt;
            BindDropDown.DataTextField = "TenDM";
            BindDropDown.DataValueField = "ID";
            BindDropDown.DataBind();
        }

        protected void ddlKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDDonVi = Convert.ToInt32(MyCommon.GetDonViID(Session["userid"].ToString()));
            IDTenBaoCao = Convert.ToInt32(ddlTenBaoCao.SelectedValue);
            IDKyBaoCao = Convert.ToInt32(ddlKyBaoCao.SelectedValue);
            DataTable dt = KiemTraBaoCaoTrungNhau(IDDonVi, IDKyBaoCao, IDTenBaoCao);
            if (dt.Rows.Count != 0)
            {
                FilePath = dt.Rows[0][6].ToString();
                txtTenBaoCao.Text = dt.Rows[0]["TenBaoCao"].ToString();
                txtNoiDung.Value = dt.Rows[0]["NoiDung"].ToString();
                IDBaoCao = Convert.ToInt32(dt.Rows[0]["ID"]);
                btnXemCiTiet.CommandArgument = MyConst.Action.Update;
                lbtFileDinhkem.Text = dt.Rows[0][6].ToString().Split('/')[2];
            }
            else
            {
                btnXemCiTiet.CommandArgument = MyConst.Action.Addnew;
                ResetField();
            }
        }

        protected void ResetField()
        {
            txtTenBaoCao.Text = "";
            lbtFileDinhkem.Text = "Không có file đính kèm";
            txtNoiDung.Value = "";
        }

        protected void ddlTenBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            IDDonVi = Convert.ToInt32(MyCommon.GetDonViID(Session["userid"].ToString()));
            IDTenBaoCao = Convert.ToInt32(ddlTenBaoCao.SelectedValue);
            IDKyBaoCao = Convert.ToInt32(ddlKyBaoCao.SelectedValue);
            DataTable dt = KiemTraBaoCaoTrungNhau(IDDonVi, IDKyBaoCao, IDTenBaoCao);
            if (dt.Rows.Count != 0)
            {
                FilePath = dt.Rows[0][6].ToString();
                txtTenBaoCao.Text = dt.Rows[0]["TenBaoCao"].ToString();
                txtNoiDung.Value = dt.Rows[0]["NoiDung"].ToString();
                IDBaoCao = Convert.ToInt32(dt.Rows[0]["ID"]);
                btnXemCiTiet.CommandArgument = MyConst.Action.Update;
                lbtFileDinhkem.Text = dt.Rows[0][6].ToString().Equals("") ? "Không có file đính kèm" : dt.Rows[0][6].ToString().Split('/')[2];
            }
            else
            {
                btnXemCiTiet.CommandArgument = MyConst.Action.Addnew;
                ResetField();
            }
        }

        protected DataTable KiemTraBaoCaoTrungNhau(int IDDonVi, int KyBaoCao, int IDBaoCao)
        {
            List<SqlParameter> arrParams = new List<SqlParameter>();
            arrParams.Add(SqlHelper.CreateParameterObject("@TenBaoCaoID", SqlDbType.Int, ParameterDirection.Input, IDBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@KyBaoCaoID_DM", SqlDbType.Int, ParameterDirection.Input, KyBaoCao));
            arrParams.Add(SqlHelper.CreateParameterObject("@DonVi_ID", SqlDbType.Int, ParameterDirection.Input, IDDonVi));
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "SELECT * FROM dbo.tblBaoCaoAttach WHERE BaoCaoAttachID_DM = @TenBaoCaoID AND KyBaoCaoID_DM = @KyBaoCaoID_DM AND DonVi_ID = @DonVi_ID", arrParams);
            return dt;
        }

        protected void lbtFileDinhkem_Click(object sender, EventArgs e)
        {
            if (FilePath.Trim().Length != 0)
            {
                string FileName = FilePath.Split('/')[2];
                Download(FileName, FilePath);
            }
        }

        public static void Download(string sFileName, string sFilePath)
        {
            HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
            String Header = "Attachment; Filename=" + sFileName;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
            System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
            HttpContext.Current.Response.WriteFile(Dfile.FullName);
            HttpContext.Current.Response.End();
        }
    }
}
